//
//  HttpResponse.m
//  Moonlight
//
//  Created by Diego Waxemberg on 1/30/15.
//  Copyright (c) 2015 Moonlight Stream. All rights reserved.
//

#import "HttpResponse.h"
#import "TemporaryApp.h"
#import <libxml2/libxml/xmlreader.h>
#include "PortManager.h"

@implementation HttpResponse {
    NSMutableDictionary* _elements;
}
@synthesize data, statusCode, statusMessage;

- (void)populateWithData:(NSData*)xml {
    self.data = xml;
    [self parseData];
}

- (NSString*)getStringTag:(NSString*)tag {
    return [_elements objectForKey:tag];
}

- (BOOL)getIntTag:(NSString *)tag value:(NSInteger*)value {
    NSString* stringVal = [self getStringTag:tag];
    if (stringVal != nil) {
        *value = [stringVal integerValue];
        return true;
    } else {
        return false;
    }
}

- (BOOL)isStatusOk {
    return self.statusCode == 200;
}

- (void)parseData {
    _elements = [[NSMutableDictionary alloc] init];
    xmlDocPtr docPtr = xmlParseMemory([self.data bytes], (int)[self.data length]);
    if (docPtr == NULL) {
        NSLog(@"An error occured trying to parse xml.");
        return;
    }
    
    xmlNodePtr node = xmlDocGetRootElement(docPtr);
    if (node == NULL) {
        NSLog(@"No root XML element.");
        xmlFreeDoc(docPtr);
        return;
    }

    xmlChar* statusStr = xmlGetProp(node, (const xmlChar*)[TAG_STATUS_CODE UTF8String]);
    if (statusStr != NULL) {
        int status = (int)[[NSString stringWithUTF8String:(const char*)statusStr] longLongValue];
        xmlFree(statusStr);
        self.statusCode = status;
    }
    
    xmlChar* statusMsgXml = xmlGetProp(node, (const xmlChar*)[TAG_STATUS_MESSAGE UTF8String]);
    if (statusMsgXml != NULL) {
        self.statusMessage = [NSString stringWithUTF8String:(const char*)statusMsgXml];
        xmlFree(statusMsgXml);
    }else {
        self.statusMessage = @"服务异常";
    }
    
    if (self.statusCode == -1 && [self.statusMessage isEqualToString:@"Invalid"]) {
        // 特殊情况下处理音频捕获错误，而GFE没有
        // 提供任何有用的状态信息。
        self.statusCode = 418;
        self.statusMessage = @"缺少音频捕捉设备。重新安装GeForce Experience应该可以解决此错误.";
    }

    node = node->children;
    
    while (node != NULL) {
        xmlChar* nodeVal = xmlNodeListGetString(docPtr, node->xmlChildrenNode, 1);
        
        NSString* value;
        if (nodeVal == NULL) {
            value = @"";
        } else {
            value = [[NSString alloc] initWithCString:(const char*)nodeVal encoding:NSUTF8StringEncoding];
        }
        
        if (value.integerValue == 47984
            || value.integerValue == 47989
            || value.integerValue == 48010
            || value.integerValue == 47998
            || value.integerValue == 47999
            || value.integerValue == 48000
            || value.integerValue == 48002) {
            unsigned short port = getCustomPortFromPortFlagIndex(value.integerValue);
            value = [NSString stringWithFormat:@"%d", port];  // 强制转换回去
            NSLog(@"\n-----serverinfo中检测到端口，进行转换，转换后的端口： %@\n", value);
        }
        
        NSString* key = [[NSString alloc] initWithCString:(const char*)node->name encoding:NSUTF8StringEncoding];
        [_elements setObject:value forKey:key];
        xmlFree(nodeVal);
        node = node->next;
    }
    
    xmlFreeDoc(docPtr);
    NSLog(@"解析过的XML数据: %@", _elements);
}


@end
